 //
//  CostViewController.m
//  iStore
//
//  Created by mirrtalk on 15/4/23.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//

#import "CostViewController.h"
#import "RequestEngine.h"
#import "Alipay.h"

@interface CostViewController ()
{
    NSString * userID;
    NSString *paySuccess;
}
@end

@implementation CostViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"付费页面";
    userID = [[NSUserDefaults standardUserDefaults]objectForKey:kUserId];
    self.navigationItem.leftBarButtonItem.title = @"返回";
    //    NSLog(@"%@",_priceDict);
   [ _certain setBackgroundImage:[UIImage imageNamed:@"Rectangle_6"] forState:UIControlStateHighlighted];
    
    
    NSDictionary *dic = @{@"userID":userID};
    [RequestEngine RequestEngineWithDic:dic URL:@"/money/checkMyMoney" completed:^(NSString *errorcode, NSDictionary *resultDict) {
        if ([errorcode isEqualToString:@"0"]) {
            _balenceMoney.text = [NSString stringWithFormat:@"%@",resultDict[@"balance"]];
        }
    }];
    NSInteger sum = [_priceDict[@"adverSum"] integerValue] * 1000;
    _priceDict[@"adverSum"] = [NSString stringWithFormat:@"%ld",(long)sum];
    
    //   NSLog(@"%@",_priceDict);
    [RequestEngine RequestEngineWithDic:_priceDict URL:@"/calculateADPrice" completed:^(NSString *errorcode, NSDictionary *resultDict) {
        if ([errorcode isEqualToString:@"0"]) {
            _costMoney.text = [NSString stringWithFormat:@"%@",resultDict];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ifSuccess:) name:kpaySuccess object:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)chooseAlipay:(id)sender {
    if (_alipayButton.selected == YES) {
        [_alipayButton setBackgroundImage:[UIImage imageNamed:@"Check-box_1.png"] forState:UIControlStateNormal];
        _alipayButton.selected = NO;
    }
    else if (_alipayButton.selected == NO) {
        [_alipayButton setBackgroundImage:[UIImage imageNamed:@"Check-box.png"] forState:UIControlStateNormal];
        _alipayButton.selected = YES;
    }
    
}
//确定
- (IBAction)certainButton:(id)sender {
    if (_alipayButton.selected == YES) {
        Alipay *alipay = [[Alipay alloc]init];
        NSDictionary *dic = @{@"userID":userID,@"money":_costMoney.text};
        [self activityStart];
        [RequestEngine userAliPayWithDic:dic completed:^(NSString *errorcode, NSDictionary *resultDict) {
            [self activityStop];
            if ([errorcode isEqualToString:@"0"]) {
                [alipay alipay:resultDict];
            }
            else{
                alert(@"请求服务器失败");
            }
        }];
        
    }
    else if ([_balenceMoney.text floatValue] < [_costMoney.text floatValue]) {
        alert(@"余额不足");
        return;
    }
    else {
        [self payAndInsert];
    }
}

//支付宝调用是否成功
- (void)ifSuccess:(NSNotification*)notification
{
    NSDictionary *userinfo = [notification userInfo];
    if ([userinfo[@"success"] isEqualToString:@"0"]) {
        [self payAndInsert];
    }
    else
        return;
}
//支付并保存
- (void)payAndInsert
{
    if ([_priceDict[@"type"] isEqualToString:@"1"]) {
        NSString *welfare = [[NSUserDefaults standardUserDefaults]objectForKey:KwealfareType];
        if (welfare.length!=0 && welfare!=nil) {
            [_priceDict setObject:welfare forKey:@"welfareType"];
        }
        
        NSFileManager *fileManager;
        if(![fileManager fileExistsAtPath:kAudioFilePath]) {
            [_priceDict setValue:_radioText forKey:@"radioText"];
        }
    }
    if ([_priceDict[@"type"] isEqualToString:@"0"]) {
        [_priceDict setValue:_radioText forKey:@"radioText"];
    }
    [_priceDict setValue:userID forKey:@"userID"];
    [_priceDict setValue:_costMoney.text forKey:@"price"];

    [self createActivity];
   
    [RequestEngine payAndInsertADWithDic:_priceDict completed:^(NSString *errorcode, NSDictionary *resultDict) {
        [[self.view viewWithTag:333] removeFromSuperview];
        if ([errorcode isEqualToString:@"0"]) {
            alert(@"支付成功");
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
            alert(@"支付失败");
    }];
}
//创建菊花圈
- (void)createActivity
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.tag = 333;
    view.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.3];
    [self.view addSubview:view];
    
    UIActivityIndicatorView *activ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activ.center = view.center;
    activ.color = [UIColor grayColor];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth/2-60, ScreenHeight/2+10, 120, 40)];
    label.text = @"订单正在提交";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor whiteColor];

    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth-160)/2, ScreenHeight/2-30, 160, 80)];
    [backView.layer setCornerRadius:10];
    backView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5f];
    
    [view addSubview:backView];
    [view addSubview:activ];
    [view addSubview:label];
    [activ startAnimating];
}
- (void)viewDidDisappear:(BOOL)animated
{
    NSInteger sum = [_priceDict[@"adverSum"] integerValue] / 1000;
    _priceDict[@"adverSum"] = [NSString stringWithFormat:@"%ld",(long)sum];
}
@end
